package cn.wang.sms.utils;

import cn.wang.sms.config.ConfigProper;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private ConfigProper configProper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //产品名称:云通信短信API产品,开发者无需替换
    final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    final String domain = "dysmsapi.aliyuncs.com";
    final Long MIN_SEND_PERIOD_IN_MILLI = 60000L;

    public SendSmsResponse sendSms(String phoneNumber, String SignName, String templateCode, String param) {
        try {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            String key = "sms:verify:phoneNumber:"+phoneNumber;
            // 发消息之前先在redis中取出数据, 验证是否在一分钟之内发送过短信
            String lastTime = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(lastTime)){
                if (System.currentTimeMillis() - Long.valueOf(lastTime)<MIN_SEND_PERIOD_IN_MILLI) {
                    log.info("[短信服务] 发送失败 发送短信时间间隔太短, 电话号码: {}",phoneNumber);
                    return null;
                }
            }

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                    configProper.getAccessKeyId(),
                    configProper.getAccessKeySecret());
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            //必填:待发送手机号
            request.setPhoneNumbers(phoneNumber);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(SignName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam(param);

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse= acsClient.getAcsResponse(request);
            log.info("[短信微服务] 短信发送成功, 电话号码: {}", phoneNumber);
            // 将发送短信的号码存入到redis中, 设置超时时长为60秒(以防止被限流)
            redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()),60, TimeUnit.SECONDS);
            return sendSmsResponse;
        } catch (ClientException e) {
            log.error("[短信微服务] 短信发送失败, 电话号码: {}", phoneNumber, e);
            return null;
        }

    }
}
